﻿using DataImporter.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataImporter.Modules
{
    public partial class ucRXA : UserControl
    {
        private List<BC> lst = new List<BC>();
        private List<BCRisk> bcRisk = new List<BCRisk>();
        private List<BCAgeAverageRisk> ageAverageRisks = new List<BCAgeAverageRisk>();

        public ucRXA()
        {
            InitializeComponent();
            this.cbbDropdown.SelectedIndex = 0;
        }

        private DBContext DBContext => new DBContext();

        private void ofdFile_FileOk(object sender, CancelEventArgs e)
        {
            var table = this.ofdFile.FileName.GetDataTable(this.cbbDropdown.SelectedItem.ToString());
            if (this.cbbDropdown.SelectedIndex == 0)
                HandleFirst(table);
            else if (this.cbbDropdown.SelectedIndex == 1)
                HandleSecond(table);
            else
                HandleThird(table);
        }

        private void HandleThird(DataTable table)
        {
            var ageRiskRow = table.Rows[4];
            var averageRiskRow = table.Rows[9];
            var ageRow = table.Rows[2];
            int start = 0, end = 0;

            for (int i = 1; i < table.Columns.Count; i++)
            {
                var age = ageRow[i].ToString();
                if (age.IsNullOrEmpty())
                    continue;

                if (age.Split('~') is String[] ages)
                {
                    start = (int)float.Parse(ages[0]);
                    end = (int)float.Parse(ages.Length > 1 ? ages[1] : ages[0]);
                }

                while (start <= end)
                {
                    ageAverageRisks.Add(new BCAgeAverageRisk
                    {
                        Age = start,
                        AgeRisk = float.Parse(ageRiskRow[i].ToString()),
                        AverageRisk = float.Parse(averageRiskRow[i].ToString())
                    });
                    start++;
                }
            }

            this.dgvData.DataSource = ageAverageRisks;
        }

        private void HandleFirst(DataTable table)
        {
            var codeIndex = 0;
            var question = string.Empty;
            var order = 0;
            var ruleIndex = 0;
            var answerIndex = 0;
            var lishu = 0;
            for (int i = 0; i < table.Columns.Count; i++)
            {
                var name = table.Rows[0][i].ToString();
                if (name.Contains("编码"))
                {
                    ruleIndex = 0;
                    codeIndex = i;
                    lishu = 0;
                }
                else if (name.Contains("规则"))
                    ruleIndex = i;
                else if (name.Contains("隶属"))
                    lishu = i;
                else if (name.Contains("指数"))
                {
                    for (int j = 1; j < table.Rows.Count; j++)
                    {
                        var row = table.Rows[j];
                        var answer = row[answerIndex].ToString()?.Trim();
                        if (string.IsNullOrWhiteSpace(answer))
                            continue;
                        lst.Add(new BC
                        {
                            Answer = answer.TrimStart('\''),
                            Score = float.Parse(row[i].ToString()),
                            Code = row[codeIndex].ToString().Trim(),
                            Order = order += 5,
                            Question = question,
                            ParentCode = lishu > 0 ? row[lishu].ToString()?.Trim() : null
                        });
                    }
                }
                else
                {
                    question = name;
                    answerIndex = i;
                }
            }

            this.dgvData.DataSource = lst;
        }

        private void HandleSecond(DataTable table)
        {
            var ageRow = table.Rows[2];
            bcRisk.Clear();

            var chuchao = string.Empty;
            var chuchan = string.Empty;
            var renshu = string.Empty;
            int start = 0, end = 0;

            for (int i = 3; i < table.Rows.Count; i++)
            {
                var row = table.Rows[i];

                if (!string.IsNullOrWhiteSpace(row[1].ToString()))
                    chuchao = row[1].ToString();
                if (!string.IsNullOrWhiteSpace(row[3].ToString()))
                    chuchan = row[3].ToString();
                renshu = row[5].ToString();
                if (string.IsNullOrWhiteSpace(renshu))
                    break;

                for (int j = 6; j < table.Columns.Count;)
                {
                    var age = ageRow[j].ToString();
                    if (age.IsNullOrEmpty())
                        continue;

                    if (age.Split('~') is String[] ages)
                    {
                        start = (int)float.Parse(ages[0]);
                        end = (int)float.Parse(ages.Length > 1 ? ages[1] : ages[0]);
                    }

                    while (start <= end)
                    {
                        bcRisk.Add(new BCRisk
                        {
                            Age = start,
                            IllCount = renshu,
                            Menarche = chuchao,
                            Primiparity = chuchan,
                            FivePersonal = float.Parse(row[j].ToString()),
                            FiveAverage = float.Parse(row[j + 1].ToString()),
                            EverPersonal = float.Parse(row[j + 2].ToString()),
                            EverAverage = float.Parse(row[j + 3].ToString()),
                        });
                        start++;
                    }
                    j += 4;
                }
            }

            this.dgvData.DataSource = bcRisk;
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            this.ofdFile.ShowDialog();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (this.cbbDropdown.SelectedIndex == 0)
            {
                if (DBContext.Db.DbMaintenance.IsAnyTable(nameof(BC)))
                    DBContext.Db.DbMaintenance.TruncateTable<BC>();
                DBContext.Db.CodeFirst.InitTables<BC>();
                DBContext.BCDB.InsertRange(lst);
            }
            else if (this.cbbDropdown.SelectedIndex == 1)
            {
                if (DBContext.Db.DbMaintenance.IsAnyTable(nameof(BCRisk)))
                    DBContext.Db.DbMaintenance.TruncateTable<BCRisk>();
                DBContext.Db.CodeFirst.InitTables<BCRisk>();
                DBContext.BCRiskDB.InsertRange(bcRisk);
            }
            else
            {
                if (DBContext.Db.DbMaintenance.IsAnyTable(nameof(BCAgeAverageRisk)))
                    DBContext.Db.DbMaintenance.TruncateTable<BCAgeAverageRisk>();
                DBContext.Db.CodeFirst.InitTables<BCAgeAverageRisk>();
                DBContext.BCAgeRisk.InsertRange(ageAverageRisks);
            }
            MessageBox.Show("保存成功");
        }
    }
}
